package com.wjjun.processor;

import com.google.auto.service.AutoService;
import com.wjjun.annotation.Print;
import com.wjjun.annotation.Test;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;

/**
 * 测试apt机制,
 */
@AutoService(Processor.class)
public class TestProcessor extends AbstractProcessor {

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);

        processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "APT启动\n");
    }

    /**
     * 要扫描的注解,返回set集合
     * @return
     */
    @Override
    public Set<String> getSupportedAnnotationTypes() {
        HashSet<String> set = new HashSet<>();
        set.add(Test.class.getCanonicalName());
        return  set;
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        //拿到所有添加Print注解的成员变量
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Test.class);
        for (Element element : elements) {
            //拿到成员变量名
            Name simpleName = element.getSimpleName();
            //输出成员变量名
            processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,simpleName + "\n");
        }

        //返回true 则后续的processor不会再处理
        return false;
    }

    /**
     * 编译版本,固定写法
     * @return
     */
    @Override
    public SourceVersion getSupportedSourceVersion() {
        return processingEnv.getSourceVersion();
    }

}
